package app.controllers;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import app.annotations.Public;
import app.models.BiometriaTemplate;
import app.models.Paciente;
import app.models.enums.StatusUsuario;
import app.services.BiometriaTemplateService;
import app.services.ConsultaService;
import app.services.PacienteService;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;

import com.google.gson.Gson;

@Resource
public class BiometriaTemplateController {

	private Result result;
	private Validator validator;
	private BiometriaTemplateService service;
	private PacienteService pacienteService;
	private HttpServletResponse response;
	private PacienteController pacienteController;
	private ConsultaService consultaService;
	
	public BiometriaTemplateController(Result result, BiometriaTemplateService service, 
			PacienteService pacienteService, Validator validator, 
			HttpServletResponse response, PacienteController pacienteController, ConsultaService consultaService){
		this.result = result;
		this.validator = validator;
		this.service = service;
		this.pacienteService = pacienteService;
		this.response = response;
		this.pacienteController = pacienteController;
		this.consultaService = consultaService;
	}
	
	@Public
	@Post("/biometria/findBiometria")
	public void findBiometria(String finger, Integer idConsulta){
		
		Paciente paciente = consultaService.findPacienteByConsultaId(idConsulta);
		
		BiometriaTemplate biometria = service.findBiometriaTemplateByPacienteIdAndByFinger(paciente.getId().intValue(), finger);
		
		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		
		String gson = new Gson().toJson(biometria.getTemplate());
		
        PrintWriter out;
		try {
			out = response.getWriter();
	        out.write(gson);
	        out.flush();
	        out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
        
        this.result.nothing();		
	}
	
	@Get("/biometria/new/{id}")
	public void newBiometria(Long id){
		Paciente paciente = pacienteService.find(id);
		BiometriaTemplate digital = service.findBiometriaTemplateByPacienteId(id.intValue());
		
		if(digital != null){
			validator.add(new ValidationMessage("Digital ja cadastrada para esse paciente.", "erro"));
		}
		
		if(StatusUsuario.INATIVO.equals(paciente.getUsuario().getStatus())){
			validator.add(new ValidationMessage("Para cadastrar uma digital o paciente deve estar ativo.", "erro"));
		} else{
			this.result.include("paciente",paciente);
		}
		
		validator.onErrorRedirectTo(this).newBiometria();
	}
	
	public void newBiometria(){}
	
	@Public
	@Post("/biometria/save")
	public void create(String finger, Integer idPaciente, String encoded){
		app.models.Result verify = new app.models.Result(true);
		
		if(finger == null || idPaciente == null || encoded == null || finger.equals("") 
				|| idPaciente.equals("") || encoded.equals("")){
			verify.setResult(false);
		}
		
		byte[] decoded = service.decodeString(encoded);
		
		BiometriaTemplate template1 = service.findBiometriaTemplateByPacienteId(idPaciente);
		
		BiometriaTemplate template = service.createTemplate(idPaciente, finger, decoded);
		
		if(template1 != null){
			verify.setResult(false);
		}
		
		if(verify.isResult()){
			service.create(template);
			pacienteController.setBiometria(template, idPaciente);
		}
		String gson = new Gson().toJson(verify);
		try {
			response.setContentType("text/plain");
			response.setCharacterEncoding("UTF-8");
	        PrintWriter out = response.getWriter();
	        out.write(gson);
	        out.flush();
	        out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.result.nothing();
	}
	
	@Get("/biometria/confirm/{id}")
	public void confirm(Long id) {
		this.result.forwardTo(this).newBiometria(id);
	}
	
}
